package com.app.miwawa.cui.system;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.framework.common.cui.AbstractController;
import org.framework.common.ext.util.DebugUtil;
import org.framework.common.ext.util.file.FileUtil.FileType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.app.miwawa.ext.util.file.ExcelUtil;

@RestController
public class ImportController extends AbstractController {
	
	@Autowired
	private JdbcTemplate jdbc;
	
	private Integer row;
	
	@RequestMapping(value = "/file/import/{sheet}")
	public Object importFile(@PathVariable final Integer sheet, @RequestParam(value = "file", required = false) MultipartFile file) {
		String[] filenames = StringUtils.split(file.getOriginalFilename(), "@");
		if (filenames.length < 2) {
			return error("Excel模版文件名称必须包含数据源信息，eg:miwawa_xxx@xxx.xlsx");
		} else {
			registerDataSource(filenames[0]);
		}

		try {
			DebugUtil.ready();
			
			String config = getConfigPath(sheet);
			ExcelUtil.readExcelImportConfig(config);
			
			ExcelUtil.readExcelContent(FileType.xlsx.name(), file.getInputStream(), sheet, new ExcelUtil.Callback() {
				@Override
				public void function(Map<String,Object> content, int index) throws Exception {
					row = ++index;
					
					System.out.println(content);
					
					String call = createSQL(content);
					
					jdbc.execute(call);
				}
			});

			DebugUtil.debug(ImportController.class, "invoke importFile method");
			
			return success("导入成功！");
		} catch (IOException e) {
			e.printStackTrace();
			return error("导入失败，请检查EXCEL模版！");
		} catch (Exception e) {
			e.printStackTrace();
			return error("导入失败，失败位置：第" + row + "行");
		}
	}
	
	private String createSQL(Map<String,Object> content){
		DebugUtil.ready();
		
		String call = ExcelUtil.sql();
		Set<String> keyset = content.keySet();
		for (String key : keyset) {
			call = call.replace(key, String.valueOf(content.get(key)));
		}
		
		System.out.println(call);
		
		DebugUtil.debug(ImportController.class, "invoke createModel method");
		return call;
	}
	
	private String getConfigPath(final int sheet){
		return new StringBuilder("/config/properties/excel.sheet[").append(sheet).append("].properties").toString();
	}
}
